﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using BLL;

public partial class TotalPlan_TotalPlanAdd : System.Web.UI.Page
{
    Authentication dllAuthentication = new Authentication();
    Model.UserInfo objUserInfo = new Model.UserInfo();
    protected void Page_Load(object sender, EventArgs e)
    {
        dllAuthentication.isLogin();
        if (!IsPostBack)
        {
            bindDropDownList(this.drpYear);
            bindDropDownList(this.drpDepartment);
            bindGridView();
        }
        if (this.gdvTotalPlan.Rows.Count == 0)
        {
            this.txtStrategicPlanSortId.Text = "1";
        }
        else
        {
            this.txtStrategicPlanSortId.Text = Convert.ToString(this.gdvTotalPlan.Rows.Count + 1);
        }
    }


    /// <summary>
    /// 绑定下拉列表
    /// </summary>
    /// <param name="_drp"></param>
    void bindDropDownList(DropDownList _drp)
    {
        if (_drp.Equals(this.drpYear))
        {
            for (int i = 2009; i < 2100; i++)
            {
                ListItem li = new ListItem(i.ToString(), i.ToString());
                _drp.Items.Add(li);
            }
            //根据系统日期自动绑定到当前年份
            string _year = DateTime.Now.Year.ToString();
            this.drpYear.SelectedIndex = this.drpYear.Items.IndexOf(this.drpYear.Items.FindByText(_year));
        }
        if (_drp.Equals(this.drpDepartment))
        {
            DepartmentInfoManager dllDepartmentInfoManager = new DepartmentInfoManager();
            DataTable dt = dllDepartmentInfoManager.getNoTree();
            this.drpDepartment.DataSource = dt;
            this.drpDepartment.DataTextField = "DepartmentName";
            this.drpDepartment.DataValueField = "DepartmentId";
            this.drpDepartment.DataBind();
            object[] _value = new object[1];
            Model.UserInfo objUserInfo = new Model.UserInfo();
            _value[0] = objUserInfo.UserName;
            UserInfoManager dllUserInfoManager = new UserInfoManager();
            DataTable _userTable = dllUserInfoManager.get(UserInfoManager.field.UserName.ToString(), _value);
            if (_userTable.Rows.Count > 0)
            {
                this.drpDepartment.SelectedIndex = this.drpDepartment.Items.IndexOf(this.drpDepartment.Items.FindByText(_userTable.Rows[0]["DepartmentId"].ToString()));
            }
        }
    }


    /// <summary>
    /// 绑定GridView
    /// </summary>
    void bindGridView()
    {
        TotalPlanMgr dllTotalPlanMgr = new TotalPlanMgr();
        object[] _value = new object[2];
        _value[0] = this.drpYear.SelectedItem.Text;
        _value[1] = this.drpDepartment.SelectedItem.Text;
        //根据年份获得总表计划
        DataTable dt = dllTotalPlanMgr.getTotalPlanByYearAndDepartment(_value);
        this.gdvTotalPlan.DataSource = dt;
        this.gdvTotalPlan.DataBind();
    }



    /// <summary>
    /// 生成DataTable
    /// </summary>
    /// <returns>DataTable</returns>
    DataTable genDataTable()
    {
        DataTable dt = new DataTable();
        DataColumn dc = new DataColumn("TotalPlanId");
        dt.Columns.Add(dc);
        dc = new DataColumn("TotalPlanSortId");
        dt.Columns.Add(dc);
        dc = new DataColumn("CompleteTime");
        dt.Columns.Add(dc);
        dc = new DataColumn("Source");
        dt.Columns.Add(dc);
        dc = new DataColumn("WorkItem");
        dt.Columns.Add(dc);
        dc = new DataColumn("MasterPeople");
        dt.Columns.Add(dc);
        dc = new DataColumn("TotalYear");
        dt.Columns.Add(dc);
        dc = new DataColumn("VerifyCircuitId");
        dt.Columns.Add(dc);
        dc = new DataColumn("WorkItemAdditional");
        dt.Columns.Add(dc);
        return dt;
    }


    /// <summary>
    /// 添加到DataTable
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        //查询部门流程id
        VerifyCircuitManager dllVerifyCircuitManager = new VerifyCircuitManager();
        object[] _valueDepartmentName = new object[1];
        _valueDepartmentName[0] = this.drpDepartment.SelectedItem.Text;
        DataTable _VerifyCircuitId = dllVerifyCircuitManager.getVerifyCircuitIdByDepartment(_valueDepartmentName);
        if (_VerifyCircuitId.Rows.Count == 0)
        {
            Utility.Error.RedirectErrorPage("所在部门无计划流程，请重试");
        }
        DataTable dt = genDataTable();
        //获取已有的记录
        dt = GridViewToDataTable(this.gdvTotalPlan, dt);
        //获得新添加的记录
        DataRow newdr = dt.NewRow();
        newdr["TotalPlanId"] = "";
        newdr["TotalPlanSortId"] = this.txtStrategicPlanSortId.Text;
        newdr["CompleteTime"] = this.txtEndDay.Text;
        newdr["Source"] = "";
        newdr["WorkItem"] = "";
        newdr["MasterPeople"] = this.txtMasterPeople.Value;
        newdr["TotalYear"] = this.drpYear.SelectedItem.Text;
        newdr["VerifyCircuitId"] = Convert.ToInt32(_VerifyCircuitId.Rows[0]["VerifyCircuitId"].ToString());
        newdr["WorkItemAdditional"] = this.txtPlanContent.Text;
        dt.Rows.Add(newdr);

        this.gdvTotalPlan.DataSource = dt;
        this.gdvTotalPlan.DataBind();
        //清空
        Clear();
    }

    void AddTotalPlan()
    {
        List<object[]> _valueList = new List<object[]>();
        int selectCount = 0;
        for (int i = 0; i < this.gdvTotalPlan.Rows.Count; i++)
        {
            //判断是否被选中
            CheckBox _ckb = (CheckBox)this.gdvTotalPlan.Rows[i].Cells[0].FindControl("ckbSelect");
            if (_ckb.Checked == true)
            {
                selectCount++;
                //判断是否已被保存过
                if (this.gdvTotalPlan.DataKeys[i]["TotalPlanId"].ToString().Length == 0 || this.gdvTotalPlan.DataKeys[i]["TotalPlanId"].ToString() == "&nbsp;")
                {
                    object[] _value = new object[9];
                    //序号
                    _value[0] = this.gdvTotalPlan.Rows[i].Cells[1].Text;
                    //结束时间
                    _value[1] = Convert.ToDateTime(this.gdvTotalPlan.Rows[i].Cells[3].Text);
                    //计划内容
                    _value[2] = this.gdvTotalPlan.Rows[i].Cells[2].Text;
                    //负责部门
                    _value[3] = this.drpDepartment.SelectedItem.Text;
                    //负责人
                    _value[4] = this.gdvTotalPlan.Rows[i].Cells[4].Text;
                    //年份
                    _value[5] = this.drpYear.SelectedItem.Text;
                    //审核流程id
                    _value[6] = Convert.ToInt32(this.gdvTotalPlan.DataKeys[i]["VerifyCircuitId"].ToString());
                    //计划状态
                    _value[7] = 0;
                    _value[8] = objUserInfo.UserName;
                    _valueList.Add(_value);
                }
            }
        }
        if (selectCount == 0)
        {
            Utility.HttpHelp.alert("请选择要保存的计划", Page);
            return;
        }
        if (_valueList.Count <= 0)
        {
            Utility.HttpHelp.alert("选择的计划已保存", Page);
            return;
        }
        if (_valueList.Count > 0)
        {
            TotalPlanMgr dllTotalPlanMgr = new TotalPlanMgr();
            int result = dllTotalPlanMgr.addWithTransaction(_valueList);
            if (result == 0)
            {
                Utility.Error.RedirectErrorPage("添加总表计划未成功，请重试！");
            }
        }
        
    }

    /// <summary>
    /// 保存计划到数据库
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSave_Click(object sender, EventArgs e)
    {
        AddTotalPlan();
        this.ckbAllSelect.Checked = false;
        bindGridView();
    }



    /// <summary>
    /// 全选事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ckbAllSelect_CheckedChanged(object sender, EventArgs e)
    {
        if (this.ckbAllSelect.Checked == true)
        {
            for (int i = 0; i < this.gdvTotalPlan.Rows.Count; i++)
            {
                CheckBox _chk = ((CheckBox)this.gdvTotalPlan.Rows[i].Cells[0].FindControl("ckbSelect"));
                _chk.Checked = true;
            }
        }
        else
        {
            for (int i = 0; i < this.gdvTotalPlan.Rows.Count; i++)
            {
                CheckBox _chk = ((CheckBox)this.gdvTotalPlan.Rows[i].Cells[0].FindControl("ckbSelect"));
                _chk.Checked = false;
            }
        }
    }


    /// <summary>
    /// 提交总表计划
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnOK_Click(object sender, EventArgs e)
    {       
        int selectCount = 0;
        List<object[]> _valueInsert = new List<object[]>();
        List<object[]> _valueUpdate = new List<object[]>();
        for (int i = 0; i < this.gdvTotalPlan.Rows.Count; i++)
        {
            //判断是否被选中
            CheckBox _ckb = (CheckBox)this.gdvTotalPlan.Rows[i].Cells[0].FindControl("ckbSelect");
            if (_ckb.Checked == true)
            {
                selectCount++;
                //判断是否已被保存过
                if (this.gdvTotalPlan.DataKeys[i]["TotalPlanId"].ToString().Length == 0 || this.gdvTotalPlan.DataKeys[i]["TotalPlanId"].ToString() == "&nbsp;")
                {
                    object[] _value = new object[9];
                    //序号
                    _value[0] = this.gdvTotalPlan.Rows[i].Cells[1].Text;
                    //结束时间
                    _value[1] = Convert.ToDateTime(this.gdvTotalPlan.Rows[i].Cells[3].Text);
                    //计划内容
                    _value[2] = this.gdvTotalPlan.Rows[i].Cells[2].Text;
                    //负责部门
                    _value[3] = this.drpDepartment.SelectedItem.Text;
                    //负责人
                    _value[4] = this.gdvTotalPlan.Rows[i].Cells[4].Text;
                    //年份
                    _value[5] = this.drpYear.SelectedItem.Text;
                    //审核流程id
                    _value[6] = Convert.ToInt32(this.gdvTotalPlan.DataKeys[i]["VerifyCircuitId"].ToString());
                    //计划状态
                    _value[7] = 1;
                    _value[8] = objUserInfo.UserName;
                    _valueInsert.Add(_value);
                }                
                else
                {
                    object[] _value = new object[1];
                    _value[0] =Convert.ToInt32(this.gdvTotalPlan.DataKeys[i]["TotalPlanId"].ToString());
                    _valueUpdate.Add(_value);
                }
            }
        }
        if (selectCount == 0)
        {
            Utility.HttpHelp.alert("请选择要保存的计划", Page);
            return;
        }        
        if (_valueInsert.Count > 0||_valueUpdate.Count>0)
        {
            TotalPlanMgr dllTotalPlanMgr = new TotalPlanMgr();
            int resultInsert = dllTotalPlanMgr.addWithTransaction(_valueInsert);
            int resultUpdate = dllTotalPlanMgr.editWithTransaction(TotalPlanMgr.field.TotalPlanId.ToString(), _valueUpdate);
            if (resultInsert == 0&&resultUpdate==0)
            {
                Utility.Error.RedirectErrorPage("提交总表计划未成功，请重试！");
            }
        }
        bindGridView();
        this.ckbAllSelect.Checked = false;
    }


    /// <summary>
    /// 删除计划
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnDel_Click(object sender, EventArgs e)
    {
        //得到button所在行        
        Button bt = (Button)sender;//获得当前控件
        TableCell cell = (TableCell)bt.Parent;//得到所处的父单元格
        GridViewRow iRow = (GridViewRow)cell.Parent;//得到所处父单元行
        int _rowIndex = iRow.RowIndex;//得到该行的索引

        DataTable dt = genDataTable();
        //获取已有的记录
        dt = GridViewToDataTable(this.gdvTotalPlan, dt);

        //删除DataTable中的记录
        dt.Rows[_rowIndex].Delete();


        //判断是否来源于战略计划,新增计划当前用户即可删除
        if (this.gdvTotalPlan.DataKeys[_rowIndex]["Source"].ToString().Length == 0 && this.gdvTotalPlan.DataKeys[_rowIndex]["TotalPlanId"].ToString().Length>0)
        {
            //获得记录id
            int TotalPlanId = Convert.ToInt32(this.gdvTotalPlan.DataKeys[_rowIndex]["TotalPlanId"].ToString());
            object[] _value = new object[1];
            _value[0] = TotalPlanId;
            TotalPlanMgr dllTotalPlanMgr = new TotalPlanMgr();
            int result = dllTotalPlanMgr.del(TotalPlanMgr.field.TotalPlanId.ToString(), _value);
            if (result == 0)
            {
                Utility.Error.RedirectErrorPage("删除总表计划未成功，请重试！");
            }
        }
        else
        {
            //判断用户是否admin
            if (objUserInfo.UserName == "admin")
            {
                //获得记录id
                int TotalPlanId = Convert.ToInt32(this.gdvTotalPlan.DataKeys[_rowIndex]["TotalPlanId"].ToString());
                object[] _value = new object[1];
                _value[0] = TotalPlanId;
                TotalPlanMgr dllTotalPlanMgr = new TotalPlanMgr();
                int result = dllTotalPlanMgr.del(TotalPlanMgr.field.TotalPlanId.ToString(), _value);
                if (result == 0)
                {
                    Utility.Error.RedirectErrorPage("删除总表计划未成功，请重试！");
                }
            }
        }
        this.gdvTotalPlan.DataSource = dt;
        this.gdvTotalPlan.DataBind();
        this.txtStrategicPlanSortId.Text = Convert.ToString(this.gdvTotalPlan.Rows.Count + 1);
    }


    /// <summary>
    /// 将GridView内容导入DataTable
    /// </summary>
    /// <returns></returns>
    DataTable GridViewToDataTable(GridView _gdv, DataTable _dt)
    {
        //获取当前GridView内容导入DataTable
        for (int i = 0; i < _gdv.Rows.Count; i++)
        {
            DataRow dr = _dt.NewRow();
            //总表计划id
            dr["TotalPlanId"]=Utility.Comm.RemoveSpecialSymbols(_gdv.DataKeys[i]["TotalPlanId"].ToString());
            //总表计划排序id
            dr["TotalPlanSortId"] = Utility.Comm.RemoveSpecialSymbols(_gdv.Rows[i].Cells[1].Text);
            //完成时间
            dr["CompleteTime"] = Utility.Comm.RemoveSpecialSymbols(_gdv.Rows[i].Cells[3].Text);
            //总表计划内容
            dr["WorkItem"] = Utility.Comm.RemoveSpecialSymbols(_gdv.Rows[i].Cells[2].Text);
            //来源
            dr["Source"] = Utility.Comm.RemoveSpecialSymbols(_gdv.DataKeys[i]["Source"].ToString());
            //负责人
            dr["MasterPeople"] = Utility.Comm.RemoveSpecialSymbols(_gdv.Rows[i].Cells[4].Text);
            //总表计划年份
            dr["TotalYear"] = Utility.Comm.RemoveSpecialSymbols(this.drpYear.SelectedItem.Text);
            dr["VerifyCircuitId"] = Utility.Comm.RemoveSpecialSymbols(_gdv.DataKeys[i]["VerifyCircuitId"].ToString());
            //dr["WorkItemAdditional"] = Utility.Comm.RemoveSpecialSymbols(_gdv.DataKeys[i]["WorkItemAdditional"].ToString());
            _dt.Rows.Add(dr);
        }
        return _dt;
    }

    /// <summary>
    /// 清空
    /// </summary>
    void Clear()
    {
        this.txtEndDay.Text = "";
        this.txtMasterPeople.Value = "";
        this.txtPlanContent.Text = "";
        this.txtStrategicPlanSortId.Text =Convert.ToString(this.gdvTotalPlan.Rows.Count + 1);

    }


    /// <summary>
    /// 部门选择事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void drpDepartment_SelectedIndexChanged(object sender, EventArgs e)
    {
        bindGridView();
        this.txtStrategicPlanSortId.Text = Convert.ToString(this.gdvTotalPlan.Rows.Count + 1);
    }

    /// <summary>
    /// 年份选择事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void drpYear_SelectedIndexChanged(object sender, EventArgs e)
    {
        bindGridView();
        this.txtStrategicPlanSortId.Text = Convert.ToString(this.gdvTotalPlan.Rows.Count + 1);
    }


    /// <summary>
    /// 处理GridView字符串
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gdvTotalPlan_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex != -1)
        {
            e.Row.Cells[3].Text = Convert.ToDateTime(e.Row.Cells[3].Text).ToShortDateString();
            e.Row.Cells[2].Text = e.Row.Cells[2].Text.Replace("&nbsp;", "");
            e.Row.Cells[9].Text = e.Row.Cells[9].Text.Replace("&nbsp;", "");
            e.Row.Cells[2].Text +=e.Row.Cells[9].Text;            
            e.Row.Cells[9].Visible = false;
        }
    }
}
